package cn.iocoder.yudao.module.im.dal.mapper;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.im.dal.dataobject.ImMessageDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 消息表 Mapper
 */
@Mapper
public interface ImMessageMapper extends BaseMapperX<ImMessageDO> {

    /**
     * 查询指定会话的消息列表
     *
     * @param conversationId 会话ID
     * @param offset 偏移量
     * @param limit 查询数量
     * @return 消息列表
     */
    default List<ImMessageDO> selectListByConversationId(Long conversationId, Integer offset, Integer limit) {
        QueryWrapper<ImMessageDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", conversationId)
                   .orderByDesc("id")
                   .last("LIMIT " + offset + ", " + limit);
        return selectList(queryWrapper);
    }

    /**
     * 查询指定会话的最新消息
     *
     * @param conversationId 会话ID
     * @return 最新消息
     */
    default ImMessageDO selectLatestByConversationId(Long conversationId) {
        QueryWrapper<ImMessageDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", conversationId)
                   .orderByDesc("id")
                   .last("LIMIT 1");
        return selectOne(queryWrapper);
    }

    /**
     * 统计指定会话的消息数量
     *
     * @param conversationId 会话ID
     * @return 消息数量
     */
    default Long countByConversationId(Long conversationId) {
        QueryWrapper<ImMessageDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", conversationId)
                   .eq("deleted", false);
        return selectCount(queryWrapper);
    }

}